<template>
  <div class="table-filter-container">
    <div :id="`${tableId}Filter`">
      <el-row class="table-filter-header">
        <el-col :span="12">
          <el-col :span="18" class="pad-rgt">
            <div class="position-relative">
              <el-input
                :placeholder="searchPlaceholder"
                v-model="inputText"
                suffix-icon="iconfont icon-sousuo"
                clearable
                size="small"
                @focus="searchFocus"
                @input="searchInput"
                @keyup.enter.native="searchEnter">
              </el-input>
              <transition name="el-zoom-in-top">
                <div
                  v-show="showSearchSuggest"
                  :style="{ height: !searchConfig.length ? '150px' : 'auto' }"
                  class="table-filter-popper table-search-suggest">
                  <TableSearchSelector
                    v-if="searchConfig.length > 0"
                    :ref="`${tableId}SearchSelect`"
                    v-model="searchResult"
                    :options="searchConfig"
                    :input-text="inputText"
                    @change="searchChange"></TableSearchSelector>
                  <div v-else>
                    <EmptyContent
                      :hide-image="true"
                      :min-height="150"
                      empty-text="暂无可用搜索项"></EmptyContent>
                  </div>
                </div>
              </transition>
            </div>
          </el-col>
          <el-col :span="6">
            <el-button
              v-if="filterConfig.length > 0"
              type="info"
              size="small"
              @click="clickFilterCtr">筛选条件&nbsp;&nbsp;
              <i
                :class="[showFilterContent ? 'prepend-icon-active' : 'prepend-icon-inactive']"
                class="el-icon-caret-bottom"></i>
            </el-button>
          </el-col>
        </el-col>
        <el-col :span="12">
          <div class="table-filter-opt-container">
            <slot name="customOpts"></slot>
            <el-tooltip
              v-if="showResetBtn"
              :open-delay="300"
              content="重置搜索、筛选条件"
              placement="top">
              <el-button
                class="table-filter-opt-btn iconfont icon-zujiantubiao-guanbi"
                @click="resetFilter">
              </el-button>
            </el-tooltip>
            <el-tooltip
              v-if="showRefresh"
              :open-delay="300"
              content="刷新表格"
              placement="top">
              <el-button
                class="table-filter-opt-btn iconfont icon-zujiantubiao-shuaxin"
                @click="clickRefresh">
              </el-button>
            </el-tooltip>
            <el-tooltip
              v-if="showColumnCtr"
              :open-delay="300"
              content="表头设置"
              placement="top">
              <el-button
                :class="{'font-color-primary color-bk-alpha-05': showColumnControl}"
                class="table-filter-opt-btn iconfont icon-kuozhanziduan"
                @click="clickColumnCtr">
              </el-button>
            </el-tooltip>
          </div>
        </el-col>
      </el-row>
      <div v-if="searchTagData.length > 0" class="mar-top-5">
        <div v-for="(group, gIdx) in searchTagData" :key="gIdx" class="display-inline-block">
          <el-tag
            v-for="(tag, tIdx) in group.tags"
            :key="tIdx"
            :disable-transitions="true"
            class="mar-rgt-5"
            size="medium"
            type="primary"
            effect="plain"
            closable
            @close="searchTagRemove(tag)">
            {{tag.label}}
          </el-tag>
        </div>
      </div>
      <div v-show="showFilterContent" class="table-filter-content">
        <div v-if="filterConfig.length > 0" class="pad-top-10">
          <div
            v-for="filter in filterConfig"
            :key="filter.key"
            class="display-inline-block mar-rgt">
            <span class="filter-item-label mar-rgt-5">{{filter.label}}</span>
            <div class="display-inline-block mar-btm-5">
              <div v-if="filter.fieldType === 'string' || filter.fieldType === 'bool'">
                <TableFilterSelector
                  v-model="filterResult[filter.key]"
                  :options="filter.options"
                  :multiple="filter.multi"
                  :placeholder="filter.label"
                  @change="filterChange"></TableFilterSelector>
              </div>
              <div v-if="filter.fieldType === 'number'">
                <TableFilterNumber
                  v-model="filterResult[filter.key]"
                  @change="filterChange"></TableFilterNumber>
              </div>
              <div v-if="filter.fieldType === 'daterange' || filter.fieldType === 'datetimerange'">
                <TableFilterDateRange
                  v-model="filterResult[filter.key]"
                  :type="filter.fieldType"
                  @change="filterChange"></TableFilterDateRange>
              </div>
              <div v-if="filter.fieldType === 'date' || filter.fieldType === 'year'">
                <TableFilterDate
                  v-model="filterResult[filter.key]"
                  :type="filter.fieldType"
                  @change="filterChange"></TableFilterDate>
              </div>
              <div v-if="filter.fieldType === 'datetime'">
                <TableFilterDateTime
                  v-model="filterResult[filter.key]"
                  :type="filter.fieldType"
                  @change="filterChange">
                </TableFilterDateTime>
              </div>
              <div v-if="filter.fieldType === 'cascade'">
                <TableFilterCascade
                  v-model="filterResult[filter.key]"
                  :options="filter.options"
                  :data-api="filter.dataApi"
                  :multiple="filter.multi"
                  @change="filterChange"></TableFilterCascade>
              </div>
            </div>
          </div>
        </div>
      </div>
      <transition name="el-zoom-in-top">
        <div v-show="showColumnControl" class="table-filter-popper table-column-control">
          <div v-if="columns.length > 0">
            <div class="header5 mar-btm-20">自定义列表项</div>
            <el-checkbox-group v-model="columnResult">
              <el-row>
                <el-col
                  v-for="(column, idx) in columns"
                  :span="8"
                  :key="idx"
                  class="pad-lft-10 pad-rgt-10 mar-btm-20">
                  <el-checkbox
                    :label="column.label"
                    :disabled="!column.checkable"
                    class="width-100"
                    size="small"
                    border>
                    {{column.label}}
                  </el-checkbox>
                </el-col>
              </el-row>
            </el-checkbox-group>
            <div class="text-align-right mar-top-10">
              <el-button type="info" size="medium" @click="cancelColumnControl">取消</el-button>
              <el-button
                type="primary"
                size="medium"
                @click="confirmColumnControl">确定
              </el-button>
            </div>
          </div>
          <div v-else>
            <EmptyContent
              :hide-image="true"
              :min-height="150"
              empty-text="暂无配置表头"></EmptyContent>
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
  import {mapState} from 'vuex';
  import {momentFormat} from '@/config/common';
  import EmptyContent from '../../EmptyContent';
  import TableFilterSelector from './TableFilterSelector';
  import TableFilterNumber from './TableFilterNumber';
  import TableFilterDateRange from './TableFilterDateRange';
  import TableFilterCascade from './TableFilterCascade';
  import TableSearchSelector from './TableSearchSelector';
  import TableFilterDate from './TableFilterDate';
  import TableFilterDateTime from './TableFilterDateTime';

  export default {
    name: 'EZTableFilter',
    components: {
      EmptyContent,
      TableFilterSelector, TableFilterNumber,
      TableFilterDateRange, TableSearchSelector,
      TableFilterCascade, TableFilterDate,
      TableFilterDateTime
    },
    props: {
      tableId: {
        type: String,
        default: ''
      },
      tableHdl: {
        type: Object,
        default: () => {
          return {};
        }
      },
      showRefresh: {
        type: Boolean,
        default: true
      },
    },
    data() {
      return {
        columns: [],
        inputText: '',
        showFilterContent: false, // 筛选条件的显示隐藏
        showSearchSuggest: false, // 搜索条件的显示隐藏
        showColumnControl: false,
        showColumnCtr: false,
        filterConfig: [],
        searchConfig: [],
        columnConfig: [],
        filterResult: {}, // 已筛选的条件
        searchResult: {}, // 已搜索的条件
        columnResult: [],
        searchTagData: [], // 已搜索的 tag 数据源
      };
    },
    computed: {
      ...mapState({
        routeParamState: state => state.routeParam.routeParamState,
      }),
      searchPlaceholder() {
        const searchLabels = _.map(this.searchConfig, 'label'); // 获取搜索条件的label属性的值返回新的数组
        return searchLabels.length > 0 ? `请输入：${searchLabels.join('、')}` : '暂无可用搜索项';
      },
      showResetBtn() {
        let hasFilter = false;
        Object.values(this.filterResult).forEach(result => {
          if (Array.isArray(result) && result.length > 0) {
            hasFilter = true;
          } else {
            const {begin, end} = result;
            if (begin || end) {
              hasFilter = true;
            }
          }
        });
        return hasFilter || this.searchTagData.length > 0;
      }
    },
    watch: {
      tableHdl: {
        handler(tableHdl) {
          if (_.isEmpty(tableHdl)) return;
          this.columns = tableHdl.columnConfig;
          this.filterConfig = tableHdl.filterConfig;
          this.searchConfig = tableHdl.searchConfig;
          this.filterResult = tableHdl.filterResult; // 已筛选的条件
          this.searchResult = tableHdl.searchResult; // 已搜索的条件
          this.assembleSearchTagData();
        },
        immediate: true,
        deep: true // tableHdl 为 TableHdl Class，需配置深度监听
      },
      showFilterContent(value) {
        if (!value) return;
        this.showSearchSuggest = false;
        this.showColumnControl = false;
      },
      showSearchSuggest(value) {
        if (!value) return;
        this.showColumnControl = false;
      },
      showColumnControl(value) {
        if (!value) return;
        this.showSearchSuggest = false;
      },
      columns(value) {
        this.columnResult = [];
        value.forEach(v => {
          // 当前列中只要有可以隐藏的就显示列表项按钮
          if (v.checkable) {
            this.showColumnCtr = true;
          }
          !v.hide && this.columnResult.push(v.label);
        });
      },
    },
    mounted() {
      // 筛选下拉 filterContent show 之后，
      // 根据当前点击区域，判断是否需要隐藏 filterContent searchContent
      document.getElementById('app').addEventListener('click', (event) => {
        const filterContent = document.getElementById(`${this.tableId}Filter`);
        if (filterContent) {
          if (!filterContent.contains(event.target)) {
            this.showSearchSuggest = false;
            this.showColumnControl = false;
          }
        }
      });
    },
    methods: {
      // 筛选相关
      clickFilterCtr() {
        this.showFilterContent = !this.showFilterContent;
      },
      filterChange() {
        this.tableHdl.updateTableParam({filter: this.filterResult});
        this.handlerChange();
      },

      // 搜索相关
      searchFocus() {
        this.showSearchSuggest = !!this.inputText;
      },
      searchInput(value) {
        this.showSearchSuggest = !!value;
      },
      // 回车搜索
      searchEnter() {
        this.showSearchSuggest = !!this.inputText;
        const searchSelect = this.$refs[`${this.tableId}SearchSelect`];
        if (!this.searchConfig.length || !this.inputText || !searchSelect) return;
        searchSelect.change(this.searchConfig[0]);
      },
      searchTagRemove(tag = {}) {
        const result = this.searchResult[tag.key];
        const valIdx = result.indexOf(tag.value);
        !!~valIdx && (result.splice(valIdx, 1));
        this.tableHdl.updateTableParam({search: this.searchResult});
        this.handlerChange();
      },
      searchChange() { // 搜索条件发生变化
        this.inputText = ''; // 清空输入框
        this.showSearchSuggest = false; // 隐藏可选择的搜索条件
        this.tableHdl.updateTableParam({search: this.searchResult});
        this.handlerChange();
      },
      // 搜索条件更改后，组装搜索 tag 数据源
      assembleSearchTagData() {
        const tagData = [];
        Object.keys(this.searchResult).forEach(key => {
          const config = this.searchConfig.find(cfg => cfg.key === key) || {}; // 当前已搜索条件对象
          const value = this.searchResult[key] || []; // 当前已搜索条件的值
          const {label} = config; // 当前已搜索条件的label值
          const group = {key, label, tags: []};
          value.forEach(v => {
            group.tags.push({ // 存储tag标签
              key, value: v,
              label: `${label}：${v}`
            });
          });
          group.tags.length > 0 && tagData.push(group);
        });
        this.searchTagData = tagData;
      },

      // 右侧 opts 相关
      clickRefresh() {
        this.showSearchSuggest = false;
        this.showColumnControl = false;
        this.inputText = '';
        this.$emit('filterChange');
      },
      // 重置所有筛选、搜索条件
      resetFilter() {
        this.tableHdl.clearTableParam();
        this.handlerChange();
      },
      clickColumnCtr() {
        this.showColumnControl = !this.showColumnControl;
      },
      cancelColumnControl() {
        this.showColumnControl = false;
      },
      confirmColumnControl() {
        this.columns.forEach(c => {
          c.hide = !this.columnResult.includes(c.label);
        });
        this.showColumnControl = false;
      },

      handlerChange() {
        // 筛选条件更改后，清空 pageNo
        this.tableHdl.updateTableParam({pageNo: 1});
        this.$emit('filterChange');
      }
    }
  };
</script>

<style scoped lang="less">
</style>
